package com.cash.loan.modular.cash.controller;

import com.cash.loan.core.upload.QiniuService;
import com.cash.loan.core.util.DateUtil;
import com.cash.loan.modular.cash.dao.LoanProductMapper;
import com.cash.loan.modular.cash.result.PageResult;
import com.cash.loan.modular.cash.result.ServerResponse;
import com.cash.loan.modular.cash.service.ProductService;
import com.cash.loan.modular.cash.transfer.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 产品管理
 *
 * @author Administrator
 * @Date 2018-07-06 11:25
 */
@Controller
@RequestMapping(value = "/cash/product")
@Api(description = "产品管理")
public class ProductController {

    private static String PREFIX = "/cash/product/";

    @Autowired
    private ProductService productService;

    @Autowired
    private QiniuService qiniuService;

    @Autowired
    private LoanProductMapper productMapper;

    /**
     * 列表页
     * @return
     */
    @RequestMapping(value = "/listPage")
    public String cashIndex() {
        return PREFIX + "product_list.html";
    }

    /**
     * 新增页
     * @return
     */
    @RequestMapping(value = "/createPage")
    public String createPage() {
        return PREFIX + "product_add.html";
    }

    /**
     * pv统计页
     * @return
     */
    @RequestMapping(value = "/pvPage")
    public String pvPage() {
        return PREFIX + "product_pv.html";
    }

    /**
     * 详情页
     * @return
     */
    @RequestMapping(value = "/detailPage")
    public String productDetailPage() {
        return PREFIX + "product_detail.html";
    }

    /**
     * 编辑页
     * @return
     */
    @RequestMapping(value = "/editPage")
    public String productEditPage() {
        return PREFIX + "product_edit.html";
    }

    @PostMapping(value = "/list")
    @ResponseBody
    @ApiOperation("产品列表")
    public ServerResponse getProductListByPage(@RequestParam(value = "currentPage",required = false,defaultValue = "1") Integer currentPage,
                                               @RequestParam(value = "pageSize",required = false,defaultValue = "20") Integer pageSize,
                                               @RequestParam(value = "keyword",required = false) String keyword,
                                               @RequestParam(value = "productFlag",required = false) Long productFlag,
                                               @RequestParam(value = "managerFlag",required = false) Long managerFlag,
                                               @RequestParam(value = "startDate",required = false) String startDate,
                                               @RequestParam(value = "endDate",required = false) String endDate) {
        Date sDate = null;

        Date eDate = null;

        if(StringUtils.isNoneBlank(startDate)) {
            sDate = DateUtil.parseDate(startDate);
        }

        if(StringUtils.isNoneBlank(endDate)) {
            eDate = DateUtil.parseDate(endDate);
        }

        ProductQueryDto queryDto = new ProductQueryDto();

        queryDto.setKeyword(keyword);

        queryDto.setProductFlag(productFlag);

        queryDto.setManageFlag(managerFlag);

        queryDto.setStartDate(sDate);

        queryDto.setEndDate(eDate);

        PageResult<ProductListVo> pageResult = productService.getProductList(currentPage,pageSize,queryDto);

        return ServerResponse.getSuccess("success",pageResult);
    }

    @ApiOperation("得到所有产品名称和id")
    @GetMapping(value = "/all")
    @ResponseBody
    public ServerResponse allProduct() {
        List<Map<String,Object>> result = productService.getAllProduct();
        return ServerResponse.getSuccess("success",result);
    }

    @ApiOperation("新建产品")
    @PostMapping(value = "/create")
    @ResponseBody
    public ServerResponse createNewProduct(@RequestBody NewProductDto newProductDto,
                                           BindingResult result) {

        if (result.hasErrors()) {
            return ServerResponse.getErrorMessage(result.getAllErrors().toString());
        }

        newProductDto.setProductIconUrl(qiniuService.getUri(newProductDto.getProductIconUrl()));

        int existCount = productMapper.existByName(newProductDto.getProductName());

        if(existCount >= 1) {
            return ServerResponse.getErrorMessage("产品已存在");
        }

        Boolean saveResult = productService.saveProduct(newProductDto);

        if(!saveResult) {
            return ServerResponse.getErrorMessage("保存失败");
        }
        return ServerResponse.getSuccess("创建成功");
    }

    @ApiOperation("更新产品状态")
    @PostMapping(value = "/updateProductStatus")
    @ResponseBody
    public ServerResponse updateProductStatus(@RequestParam(value = "productId") Long productId,
                                              @RequestParam(value = "productFlag") Long productFlag) {
        if(productFlag == null || productId == null) {
            return ServerResponse.getErrorMessage("参数不能为空");
        }

        if(productFlag < 0 || productFlag > 3) {
            return ServerResponse.getErrorMessage("产品状态码错误");
        }

        Boolean updateResult = productService.updateProductStatus(productId,productFlag);

        if(!updateResult) {
            return ServerResponse.getErrorMessage("更新产品状态失败");
        }
        return ServerResponse.getSuccess("更新产品状态成功");
    }

    @ApiOperation("更新管理状态")
    @PostMapping(value = "/updateManageStatus")
    @ResponseBody
    public ServerResponse updateManageStatus(@RequestParam(value = "productId") Long productId,
                                              @RequestParam(value = "manageFlag") Long manageFlag) {
        if(manageFlag == null || productId == null) {
            return ServerResponse.getErrorMessage("参数不能为空");
        }

        if(manageFlag < 0 || manageFlag > 2) {
            return ServerResponse.getErrorMessage("管理状态码错误");
        }

        Boolean updateResult = productService.updateManageStatus(productId,manageFlag);

        if(!updateResult) {
            return ServerResponse.getErrorMessage("更新管理状态失败");
        }
        return ServerResponse.getSuccess("更新管理状态成功");
    }

    @ApiOperation("更新管理状态")
    @PostMapping(value = "/updateDownloadStatus")
    @ResponseBody
    public ServerResponse updateDownloadStatus(@RequestParam(value = "productId") Long productId,
                                             @RequestParam(value = "downloadFlag") Long downloadFlag) {
        if(downloadFlag == null || productId == null) {
            return ServerResponse.getErrorMessage("参数不能为空");
        }

        if(downloadFlag < 0 || downloadFlag > 2) {
            return ServerResponse.getErrorMessage("下载状态码错误");
        }

        Boolean updateResult = productService.updateDownloadStatus(productId,downloadFlag);

        if(!updateResult) {
            return ServerResponse.getErrorMessage("更新下载状态失败");
        }
        return ServerResponse.getSuccess("更新下载状态成功");
    }

    /**
     * 详情页面
     * @param productId
     * @return
     */
    @ApiOperation("产品详情页")
    @GetMapping(value = "/detail")
    @ResponseBody
    public ServerResponse getProductDetail(@RequestParam(value = "productId") Long productId) {
        ProductDetailMapVo mapVo = productService.productDetail(productId);
        if(mapVo == null) {
            return ServerResponse.getSuccess("success",new HashMap<>(1));
        }
        return ServerResponse.getSuccess("success",mapVo);
    }

    @ApiOperation("产品修改")
    @PostMapping(value = "/update")
    @ResponseBody
    public ServerResponse updateProduct(@RequestBody UpdateProductDto productDto,
                                        BindingResult result) {
        if (result.hasErrors()) {
            return ServerResponse.getErrorMessage(result.getAllErrors().toString());
        }

        productDto.setProductIconUrl(qiniuService.getUri(productDto.getProductIconUrl()));

        Boolean updateResult = productService.updateProductStatus(productDto);

        if(!updateResult) {
            return ServerResponse.getErrorMessage("修改产品失败");
        }

        return ServerResponse.getSuccess("修改产品成功");
    }

    @ApiOperation("每日pv统计集合")
    @GetMapping(value = "/dayPv")
    @ResponseBody
    public ServerResponse productPvUv(@RequestParam(value = "currentPage",required = false,defaultValue = "1") Integer currentPage,
                                      @RequestParam(value = "pageSize",required = false,defaultValue = "20") Integer pageSize,
                                      @RequestParam(value = "productId") Long productId) {
        PageResult<Map<String,Object>> result = productService.listProductPvAndUv(currentPage,pageSize,productId);
        return ServerResponse.getSuccess("success",result);
    }

    @ApiOperation("更改排序值")
    @PostMapping(value = "/orderNum")
    @ResponseBody
    public ServerResponse changeOrderNum(@RequestParam(value = "id") Integer id,
                                         @RequestParam(value = "orderNum") Integer orderNum) {
        if(orderNum < 0) {
            return ServerResponse.getErrorMessage("排序值不能为负数");
        }
        Boolean result = productService.changeOrderNum(id,orderNum);
        if(!result) {
            return ServerResponse.getErrorMessage("更改排序值失败");
        }
        return ServerResponse.getSuccess("更改排序值成功");
    }
}
